#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
#include "mytbf.h"

#define CPS 10
#define BUFSIZE 1024
#define BURST 100

int main(int argc, char **argv)
{
  int sfd, dfd = 1;
  char buf[BUFSIZE];
  int len, ret, pos, token_nums;
  mytbf_t *tbf;

  if (argc < 2) {
    fprintf(stderr, "Usage...\n");
    exit(1);
  }

  tbf = mytbf_init(CPS, BURST);
  if (tbf == NULL) {
    fprintf(stderr, "tbf is NULL\n"); 
    exit(1);
  }

  do {
    if ((sfd = open(argv[1], O_RDONLY)) < 0) {
      if (errno != EINTR) {
        perror("open()");
	exit(1);
      }
    }
  } while (sfd < 0);

  while (1) {
    token_nums = mytbf_fetchtoken(tbf, BUFSIZE);

    while ((len = read(sfd, buf, token_nums)) < 0) {
      if (errno == EINTR) 
        continue;
      perror("read()");
      break;
    }
    if (len == 0) 
      break;
   
    // return token which did not used
    if (token_nums - len > 0) {
      mytbf_returntoken(tbf, token_nums - len);
    }

    pos = 0;
    while (len > 0) {
      ret = write(dfd, buf + pos, len);
      if (ret < 0) {
        if (errno == EINTR) 
          continue;
	perror("write()");
	exit(1);
      }
      pos += ret;
      len -= ret;
    }
  }
  
  close(sfd);
  mytbf_destroy(tbf);

  exit(0);

}
